<template>
  <div class="message-board">
    <div class="board-header">
      <h2>留言板</h2>
      <el-button type="primary" @click="handleAddMessage" v-if="isLoggedIn">
        发布留言
      </el-button>
    </div>

    <!-- 留言列表 -->
    <div v-loading="loading" class="message-list">
      <div v-if="messages.length === 0" class="empty-messages">
        <el-empty description="暂无留言" />
      </div>

      <div v-else class="messages-container">
        <el-card v-for="message in messages" :key="message.id" class="message-card">
          <div class="message-header">
            <div class="user-info">
              <span class="username">{{ message.username || message.user?.username || '匿名用户' }}</span>
              <span class="time">{{ formatDate(message.createTime) }}</span>
            </div>
            <div v-if="isLoggedIn && message.userId === currentUserId" class="message-actions">
              <el-button type="text" @click="handleEditMessage(message)">编辑</el-button>
              <el-button type="text" @click="handleDeleteMessage(message)">删除</el-button>
            </div>
          </div>

          <div class="message-content">
            <p>{{ message.content }}</p>
          </div>

          <div v-if="message.isReplied" class="message-reply">
            <div class="reply-header">
              <el-icon><ChatDotRound /></el-icon>
              <span class="reply-label">管理员回复：</span>
              <span class="reply-time">{{ formatDate(message.replyTime) }}</span>
            </div>
            <div class="reply-content">
              <p>{{ message.reply }}</p>
            </div>
          </div>

          <div v-else-if="isAdmin" class="message-actions-admin">
            <el-button type="primary" size="small" @click="handleReplyMessage(message)">
              回复
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 发布/编辑留言对话框 -->
    <el-dialog
      v-model="messageDialogVisible"
      :title="isEditing ? '编辑留言' : '发布留言'"
      width="500px"
    >
      <el-form
        ref="messageFormRef"
        :model="messageForm"
        :rules="messageRules"
        label-width="80px"
      >
        <el-form-item label="留言内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入留言内容..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="messageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleMessageSubmit" :loading="submitting">
            {{ isEditing ? '更新' : '发布' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 回复留言对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复留言"
      width="500px"
    >
      <div v-if="currentMessage" class="reply-dialog">
        <div class="original-message">
          <div class="message-header">
            <span class="username">{{ currentMessage.user?.username }}</span>
            <span class="time">{{ formatDate(currentMessage.createTime) }}</span>
          </div>
          <div class="message-content">
            <p>{{ currentMessage.content }}</p>
          </div>
        </div>
        <el-form
          ref="replyFormRef"
          :model="replyForm"
          :rules="replyRules"
          label-width="80px"
        >
          <el-form-item label="回复内容" prop="reply">
            <el-input
              v-model="replyForm.reply"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容..."
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReplySubmit" :loading="submitting">
            回复
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ChatDotRound } from '@element-plus/icons-vue'
import { getAllMessages, addMessage, updateMessage, deleteMessage, replyMessage } from '@/api/message'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const messages = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框控制
const messageDialogVisible = ref(false)
const replyDialogVisible = ref(false)
const isEditing = ref(false)
const currentMessage = ref(null)

// 表单数据
const messageFormRef = ref(null)
const replyFormRef = ref(null)

const messageForm = ref({
  content: ''
})

const replyForm = ref({
  reply: ''
})

// 表单验证规则
const messageRules = {
  content: [
    { required: true, message: '请输入留言内容', trigger: 'blur' },
    { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
  ]
}

const replyRules = {
  reply: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const isLoggedIn = computed(() => userStore.isLoggedIn)
const currentUserId = computed(() => userStore.user?.id)
const isAdmin = computed(() => userStore.user?.role === 'ADMIN')

// 加载留言列表
const loadMessages = async () => {
  loading.value = true
  try {
    const res = await getAllMessages()
    if (res.code === 200) {
      messages.value = res.data
    } else {
      ElMessage.error(res.message || '获取留言失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取留言失败')
  } finally {
    loading.value = false
  }
}

// 发布留言
const handleAddMessage = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  isEditing.value = false
  messageForm.value.content = ''
  messageDialogVisible.value = true
}

// 编辑留言
const handleEditMessage = (message) => {
  isEditing.value = true
  messageForm.value.content = message.content
  messageDialogVisible.value = true
}

// 删除留言
const handleDeleteMessage = async (message) => {
  try {
    await ElMessageBox.confirm('确定要删除该留言吗？', '提示', {
      type: 'warning'
    })
    await deleteMessage(message.id)
    ElMessage.success('删除成功')
    await loadMessages()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }
}

// 回复留言
const handleReplyMessage = (message) => {
  currentMessage.value = message
  replyForm.value.reply = ''
  replyDialogVisible.value = true
}

// 提交留言
const handleMessageSubmit = async () => {
  if (!messageFormRef.value) return
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }

  await messageFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (isEditing.value) {
          await updateMessage({
            id: currentMessage.value.id,
            content: messageForm.value.content
          })
          ElMessage.success('更新成功')
        } else {
          await addMessage({
            content: messageForm.value.content,
            userId: userStore.userInfo.id,
            username: userStore.userInfo.username
          })
          ElMessage.success('发布成功')
        }
        messageDialogVisible.value = false
        await loadMessages()
      } catch (error) {
        console.error(error)
        ElMessage.error(isEditing.value ? '更新失败' : '发布失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 提交回复
const handleReplySubmit = async () => {
  if (!replyFormRef.value) return

  await replyFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await replyMessage(currentMessage.value.id, replyForm.value.reply)
        ElMessage.success('回复成功')
        replyDialogVisible.value = false
        await loadMessages()
      } catch (error) {
        console.error(error)
        ElMessage.error('回复失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadMessages()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadMessages()
}

// 工具函数
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  loadMessages()
})
</script>

<style scoped>
.message-board {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.board-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.board-header h2 {
  margin: 0;
  color: #333;
}

.message-list {
  margin-top: 20px;
}

.empty-messages {
  text-align: center;
  padding: 40px 0;
}

.messages-container {
  margin-bottom: 20px;
}

.message-card {
  margin-bottom: 20px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  font-weight: bold;
  color: #409eff;
}

.time {
  color: #999;
  font-size: 14px;
}

.message-actions {
  display: flex;
  gap: 10px;
}

.message-content {
  margin-bottom: 15px;
}

.message-content p {
  margin: 0;
  line-height: 1.6;
  color: #333;
}

.message-reply {
  background-color: #f8f9fa;
  border-left: 4px solid #409eff;
  padding: 15px;
  margin-top: 15px;
  border-radius: 4px;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  color: #409eff;
}

.reply-label {
  font-weight: bold;
}

.reply-time {
  color: #999;
  font-size: 14px;
}

.reply-content p {
  margin: 0;
  line-height: 1.6;
  color: #333;
}

.message-actions-admin {
  margin-top: 15px;
  text-align: right;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.reply-dialog .original-message {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}
</style> 